<?php
namespace Home\Controller;

class LoginController extends CommonController{

	public function index(){
	    //如果已经登录，则调到首页
	    if(session('user'))exit($this->redirect('Index/index'));
	    //记录上一次的链接
        if($_SERVER['HTTP_REFERER'])session(C('LAST_URL'),$_SERVER['HTTP_REFERER']);
	    $this->display();
    }
    public function register() {
        //如果已经登录，则调到首页
        if(session('user'))exit($this->redirect('Index/index'));
        
        $this->display();
    }
    public function resetPwd() {
        //如果已经登录，则调到首页
        if(session('user'))exit($this->redirect('Index/index'));
        
        $this->display();
    }
    public function doLogin(){
        $data = I('post.info');
        if(!$this->check_user($data['username'],$data['password'])){
            $this->error('用户名或密码错误！');
        }
        vendor("Captcha.captcha");
        $validator = new \Captcha();
        if (!$validator->check_word(I('post.yzcode'))){
            session('user',null);//登录失败，上一步存入session的用户数据删除
            $this->error('验证码错误！');
        }

        if($redirect_url = session(C('LAST_URL'))){
            session(C('LAST_URL'),null);
        }else{
            $redirect_url = U('Index/index');
        }
        $this->success('登录成功！',$redirect_url);
    }
    public function doRegister(){
        //判断用户名是否重复
        $mobile_phone = I('post.mobile_phone');
        $password = I('post.password');
        $repassword = I('post.repassword');
        $where = array();
        $where['user_name|mobile_phone'] = $mobile_phone;
        $user_data = D('Users')->where($where)->find();
        if(!empty($user_data)){
            $this->error('该手机号已存在！');
        }
        //校验短信验证码
        $this->checkSmsCode(I('post.smscode'));
        //校验图形验证码
        vendor("Captcha.captcha");
        $validator = new \Captcha();
        if (!$validator->check_word($_POST['yzcode'])){
            $this->error('验证码错误！');
        }
        //验证两次输入的密码是否一致
        if($password != $repassword)$this->error('两次输入的密码不一致！');
        
        //插入user表，存session
        // $insert_data['user_name'] = random_user();
        $insert_data['user_name'] = $mobile_phone;
        $insert_data['fromuser'] = $this->fromuser;
        $insert_data['mobile_phone'] = $mobile_phone;
        $insert_data['password'] = compile_password(array('password'=>$password));
        $insert_data['reg_time'] = time();
        D('Users')->add($insert_data);
        $user_msg = D('Users')->where("user_name='{$insert_data['user_name']}'")->find();
        session('user',$user_msg);

        /* 注册送积分 */
        $shop_config = $this->get_shop_config();
        if (!empty($shop_config['register_points']))
        {
            $this->log_account_change($user_msg['user_id'], 0, 0, $shop_config['register_points'], $shop_config['register_points'], '注册积分');
        }
        $this->sendWebMsg('恭喜您注册成功！请等待管理员审核。',$user_msg['user_id']);//站内消息
        /* $this->sendTmpMsg($customer_id,$fromuser,array(
            'url'=>C('WEB_DOMAIN').U('Ucenter/index'),
            'first'=>'恭喜您注册成功！',
            'keyword1'=>$insert_data['mobile_phone'],
            'keyword2'=>date('Y-m-d H:i:s'),
            'remark'=>'请耐心等待管理员审核。'
        ),1); *///微信模板消息
        if($redirect_url = session(C('LAST_URL'))){
            session(C('LAST_URL'),null);
        }else{
            $redirect_url = U('Index/index');
        }
        $this->success('注册成功！',$redirect_url);
    }
    
    public function savePwd(){
        //判断用户名是否重复
        $mobile_phone = I('post.mobile_phone');
        $password = I('post.password');
        $repassword = I('post.repassword');
        $where = array();
        $where['user_name|mobile_phone'] = $mobile_phone;
        $user_data = D('Users')->where($where)->find();
        if(empty($user_data)){
            $this->error('该手机号不存在！');
        }
        //校验短信验证码
        $this->checkSmsCode(I('post.smscode'));
        //校验图形验证码
//         vendor("Captcha.captcha");
//         $validator = new \Captcha();
//         if (!$validator->check_word($_POST['yzcode'])){
//             $this->error('验证码错误！');
//         }
        //验证两次输入的密码是否一致
        if($password != $repassword)$this->error('两次输入的密码不一致！');
        
        //更新密码
        $update_data['fromuser'] = $this->fromuser;
        $update_data['password'] = compile_password(array('password'=>$password,'ec_salt'=>$user_data['ec_salt']));
        $update_data['last_login'] = time();
        $update_data['last_time'] = date();
        $update_data['last_ip'] = GetIP();

        D('Users')->where(array('user_id'=>$user_data['user_id']))->save($update_data);
        session('user',D('Users')->find($user_data['user_id']));

        $this->sendWebMsg('恭喜您，重置密码成功!',$user_msg['user_id']);//站内消息

        if($redirect_url = session(C('LAST_URL'))){
            session(C('LAST_URL'),null);
        }else{
            $redirect_url = U('Index/index');
        }
        $this->success('重置密码成功！',$redirect_url);
    }
    
    /**
     * 检查指定用户是否存在及密码是否正确(重载基类check_user函数，支持zc加密方法)
     * @access  public
     * @param   string  $username   用户名
     * @return  int
     */
    public function check_user($username, $password)
    {
        $row = D('Users')->field("user_id,password,salt,ec_salt")->where("user_name='$username'")->find();
        if (empty($row))return false;
        $ec_salt = $row['ec_salt'];
    
        if (empty($row['salt']))
        {
            if ($row['password'] != compile_password(array('password'=>$password,'ec_salt'=>$ec_salt))){
                return false;
            }else{
                if(empty($ec_salt)){
                    $ec_salt = rand(1,9999);
                    $new_password = md5(md5($password).$ec_salt);
                    D()->execute("UPDATE `sc_users` SET password= '$new_password',ec_salt='$ec_salt' WHERE user_name='$username'");
                }
                //更新登陆信息
                $this->update_user($row['user_id']);
                return true;
            }
        }else{
            /* 如果salt存在，使用salt方式加密验证，验证通过洗白用户密码 */
            $encrypt_type = substr($row['salt'], 0, 1);
            $encrypt_salt = substr($row['salt'], 1);
            
            /* 计算加密后密码 */
            $encrypt_password = '';
            switch ($encrypt_type){
                case "1" :$encrypt_password = md5($encrypt_salt.$password);break;
                case "2" :$encrypt_password = md5(md5($password).$encrypt_salt);break;
                default:$encrypt_password = '';
            }
            if ($row['password'] != $encrypt_password){
                return false;
            }
            D()->execute("UPDATE `sc_users` SET password = '".compile_password(array('password'=>$password))."', salt='' WHERE user_id = '$row[user_id]'");
            //更新登陆信息
            $this->update_user($row['user_id']);
            return true;
        }
    }

    
    public function update_user($user_id){
    	if(empty($user_id)||!is_numeric($user_id))return false;
    	$user_data = D('Users')->where("user_id='$user_id'")->find();
    	if(empty($user_data)){
    		return false;
    	}else{
    		$update_data = array();
    		$update_data['fromuser'] = $this->fromuser;
    		$update_data['visit_count'] = 'visit_count + 1';
    		$update_data['last_ip'] = GetIP();
    		$update_data['last_login'] = time();
    		D('Users')->where("user_id='$user_id'")->save($update_data);
    		//存入session
    		session('user',$user_data);
    		return true;
    	}
    }
    
    public function sendCode() {
        if(session('smstime')){
            if(time()-session('smstime')<=60)$this->error('验证码发送太过频繁');
        }
        $smscode = sendSMS(I('post.telephone'));
        if($smscode){
            session('smscode',$smscode);
            session('smstime',time());
            $this->success($smscode);
        }else{
            $this->error('无效的手机号！');
        }
    }
    
    /**
     * 校验验证码
     * @param unknown $code
     */
    private function checkSmsCode($code) {
        if(empty($code)) $this->error('请输入短信验证码');
        if($code != session('smscode'))$this->error('短信验证码错误');
        if(time()-session('smstime')>60)$this->error('短信验证码已过期');
        session('smscode',null);
        session('smstime',null);
    }
    
    /**
     * 验证是否在有效时间内已经发送过短信验证码
     */
    private function hasSmsCode(){
        if(session('smscode')){
            if(time()-session('smstime')<=60){
                return true;
            }else{
                session('smscode',null);
                session('smstime',null);
                return false;
            }
        }else{
            return false;
        }
    }
    
    /**
     * 记录帐户变动
     * @param   int     $user_id        用户id
     * @param   float   $user_money     可用余额变动
     * @param   float   $frozen_money   冻结余额变动
     * @param   int     $rank_points    等级积分变动
     * @param   int     $pay_points     消费积分变动
     * @param   string  $change_desc    变动说明
     * @param   int     $change_type    变动类型：参见常量文件
     * @return  void
     */
    private function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = ACT_OTHER)
    {
        /* 插入帐户变动记录 */
        $account_log = array(
            'user_id'       => $user_id,
            'user_money'    => $user_money,
            'frozen_money'  => $frozen_money,
            'rank_points'   => $rank_points,
            'pay_points'    => $pay_points,
            'change_time'   => gmtime(),
            'change_desc'   => $change_desc,
            'change_type'   => $change_type
        );
        D('AccountLog')->add($account_log);
        /* 更新用户信息 */
        $sql = "UPDATE `sc_users` " .
            " SET user_money = user_money + ('$user_money')," .
            " frozen_money = frozen_money + ('$frozen_money')," .
            " rank_points = rank_points + ('$rank_points')," .
            " pay_points = pay_points + ('$pay_points')" .
            " WHERE user_id = '$user_id' LIMIT 1";
        D()->execute($sql);
    }
    
    /**
     * 获取店铺参数
     */
    private function get_shop_config(){
        $arr = array();
        $config = M('ShopConfig')->field("code,value")->where("parent_id>0")->find();
        foreach ($arr as $key=>$val){
            $arr[$val['code']] = $val['value'];
        }
        return $arr;
    }
}